package com.ypan.monitor.views;

import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.ypan.monitor.BaseFragment;
import com.ypan.monitor.R;
import com.ypan.monitor.osutils.Cpu;

public class CPUFragment extends BaseFragment {

	private CPUAdapter adapter;

	public static CPUFragment newInstance() {
		CPUFragment fragment = new CPUFragment();
		return fragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return initView(inflater, container, savedInstanceState);
	}

	private View initView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.listview, container, false);
		ListView lv = (ListView) view.findViewById(R.id.list);
		adapter = new CPUAdapter(getActivity());
		lv.setAdapter(adapter);
		return view;
	}

	@Override
	public void onLoadData(boolean bforceUpdate) {
		refreshData();
	}

	private Handler handler = new Handler();
	private Runnable r = new Runnable() {

		@Override
		public void run() {
			refreshData();
			handler.postDelayed(r, 3000);
		}
	};

	@Override
	public void onPause() {
		super.onPause();
		handler.removeCallbacks(r);
	}

	@Override
	public void onResume() {
		super.onResume();
		handler.postDelayed(r, 3000);
	}

	private void refreshData() {
		Cpu.getInstance(getActivity()).refresh();
		if (adapter != null)
			adapter.update();
	}
}
